package com.zyh.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zyh.appointment.domain.Appointment;
import com.zyh.appointment.service.IAppointmentService;
import com.zyh.common.core.controller.BaseController;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.core.domain.entity.SysUser;
import com.zyh.common.core.page.TableDataInfo;
import com.zyh.common.core.redis.RedisCache;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.counselor.domain.Counselor;
import com.zyh.counselor.service.ICounselorService;
import com.zyh.system.service.ISysUserService;
import com.zyh.websocket.constant.MessageConstant;
import com.zyh.websocket.entity.Message;
import com.zyh.websocket.service.chat.MessageService;
import com.zyh.websocket.vo.ChatVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ZYH
 * @version 1.0
 * @date 2025-04-02
 */
@RequestMapping("/chatUser/chatUser")
@RestController
public class ChatController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IAppointmentService appointmentService;

    @Autowired
    private ICounselorService counselorService;

    @Autowired
    private MessageService messageService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 咨询师获取发送过咨询消息的用户列表
     *
     * @return
     */
    @GetMapping("/getUserList")
    public TableDataInfo getUserList() {
        logger.info("进入咨询师获取用户消息方法");
        // 咨询师登录拿到自己的id
        Long counselorId = SecurityUtils.getUserId();
        List<ChatVO> chatVOList;
        //  先从redis里面查询
        chatVOList = redisCache.getCacheList(MessageConstant.SubType.USER_TO_CONSULTANT + counselorId);
        if (!chatVOList.isEmpty()) {
            return getDataTable(chatVOList);
        } else {
            // 从消息表中查询有没有用户给自己发送消息。
            List<Message> messageList = messageService.list(new LambdaQueryWrapper<Message>()
                    .eq(Message::getReceiverId, counselorId)
                    .eq(Message::getType, MessageConstant.CHAT_MSG)
                    .eq(Message::getSubType, MessageConstant.SubType.USER_TO_CONSULTANT)
                    .eq(Message::getDelFlag, "0")
            );
            if (messageList.isEmpty()) {
                return null;
            }
            Set<Long> userIdSet = messageList.stream().map(Message::getSenderId).collect(Collectors.toSet());
            List<SysUser> userList = userService.listByIds(userIdSet);
            chatVOList = userList.stream().map(user -> {
                ChatVO vo = new ChatVO();
                vo.setUserId(user.getUserId());
                vo.setUserName(user.getUserName());
                vo.setAvatar(user.getAvatar());
                return vo;
            }).collect(Collectors.toList());
            redisCache.setCacheList(MessageConstant.SubType.USER_TO_CONSULTANT + counselorId, userList);
        }
        return getDataTable(chatVOList);
    }

    /**
     * 用户端获取所有的咨询师列表
     *
     * @return
     */
    @GetMapping("/getCounselorChatList")
    public TableDataInfo getCounselorChatList() {
        List<Counselor> counselorList = counselorService.list();
        Set<Long> userIdList = counselorList.stream().map(Counselor::getUserId).collect(Collectors.toSet());
        List<SysUser> userList = userService.listByIds(userIdList);
        List<ChatVO> chatVOList = userList.stream().map(user -> {
            ChatVO vo = new ChatVO();
            vo.setUserId(user.getUserId());
            vo.setUserName(user.getUserName());
            vo.setAvatar(user.getAvatar());
            return vo;
        }).collect(Collectors.toList());
        return getDataTable(chatVOList);
    }

    /**
     * 获取咨询师列表
     *
     * @return
     */
    /*@GetMapping("/getCounselorChatList")
    public TableDataInfo getCounselorChatList() {
        startPage();
        // 查询当前用户的所有有效预约记录
        List<Appointment> appointmentList = appointmentService.list(
                new LambdaQueryWrapper<Appointment>()
                        .eq(Appointment::getUserId, SecurityUtils.getUserId())
                        .eq(Appointment::getDelFlag, "0")
        );
        if (appointmentList.isEmpty()) {
            return null;
        }

        // 提取咨询师 ID 并去重
        Set<Long> counselorIdSet = Optional.ofNullable(appointmentList)
                .orElseGet(Collections::emptyList)
                .stream()
                .map(Appointment::getCounselorId)
                .collect(Collectors.toSet());

        // 查询咨询师信息
        List<Counselor> counselorList = counselorService.listByIds(
                counselorIdSet.isEmpty() ? Collections.emptyList() : new ArrayList<>(counselorIdSet)
        );

        // 提取用户 ID 并去重
        Set<Long> userIdSet = Optional.ofNullable(counselorList)
                .orElseGet(Collections::emptyList)
                .stream()
                .map(Counselor::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 查询用户信息
        List<SysUser> userList = userService.listByIds(
                userIdSet.isEmpty() ? Collections.emptyList() : new ArrayList<>(userIdSet)
        );

        // 转换为 VO 列表
        List<ChatVO> chatVOList = Optional.ofNullable(userList)
                .orElseGet(Collections::emptyList)
                .stream()
                .map(user -> {
                    ChatVO vo = new ChatVO();
                    vo.setId(user.getUserId());
                    vo.setName(user.getUserName());
                    vo.setAvatar(user.getAvatar());
                    return vo;
                })
                .collect(Collectors.toList());

        return getDataTable(chatVOList);
    }*/

    /**
     * 获取所有联系人
     *
     * @return
     */
    @GetMapping("/getAllChatList")
    public TableDataInfo getAllChatList() {
        startPage();
        List<SysUser> userList = userService.list(new LambdaQueryWrapper<SysUser>()
                .ne(SysUser::getUserId, SecurityUtils.getUserId())
                .eq(SysUser::getDelFlag, "0"));
        List<ChatVO> chatVOList = userList.stream().map(user -> {
                    ChatVO vo = new ChatVO();
                    vo.setUserId(user.getUserId());
                    vo.setUserName(user.getUserName());
                    vo.setAvatar(user.getAvatar());
                    return vo;
                })
                .collect(Collectors.toList());
        return getDataTable(chatVOList);
    }

    /**
     * 获取自己的所有的历史消息
     *
     * @return
     */
    @GetMapping("/getHistoryMsg")
    public TableDataInfo getHistoryMsg(@RequestParam("currentUserId") Long currentUserId,
                                       @RequestParam("contactId") Long contactId) {
        startPage();
        List<Message> messageList = messageService.list(new LambdaQueryWrapper<Message>()
                .and(wrapper -> {
                    wrapper.eq(Message::getSenderId, currentUserId)
                            .eq(Message::getReceiverId, contactId)
                            .eq(Message::getType, MessageConstant.CHAT_MSG)
                            .eq(Message::getSubType, MessageConstant.SubType.USER_TO_CONSULTANT)
                            .or()
                            .eq(Message::getSenderId, contactId)
                            .eq(Message::getReceiverId, currentUserId)
                            .eq(Message::getType, MessageConstant.CHAT_MSG)
                            .eq(Message::getSubType, MessageConstant.SubType.USER_TO_CONSULTANT);
                })
                .orderByAsc(Message::getSendTime));
        return getDataTable(messageList);
    }

    /**
     * 获取我的站内信
     */
    @GetMapping("/getMyInboxMessages")
    public TableDataInfo getMyInboxMessages(Message message) {
        logger.info("获取我的站内信-->{}", message);
        message.setReceiverId(SecurityUtils.getUserId());
        startPage();
        List<Message> messageList = messageService.getMyInboxMessages(message);
        return getDataTable(messageList);
    }

    /**
     * 消息已读
     *
     * @param messageId
     * @return
     */
    @PutMapping("/read/{messageId}")
    public AjaxResult read(@PathVariable("messageId") Long messageId) {
        return toAjax(messageService.update(new LambdaUpdateWrapper<Message>()
                .eq(Message::getMessageId, messageId)
                .eq(Message::getDelFlag, "0")
                .set(Message::getIsRead, "1")));
    }

    /**
     * 获取消息详情
     *
     * @param messageId
     * @return
     */
    @GetMapping("/{messageId}")
    public AjaxResult getInfo(@PathVariable Long messageId) {
        return AjaxResult.success(messageService.getById(messageId));
    }

    /**
     * 删除消息
     *
     * @param messageId
     * @return
     */
    @DeleteMapping("/{messageId}")
    public AjaxResult delete(@PathVariable Long messageId) {
        return toAjax(messageService.update(new LambdaUpdateWrapper<Message>()
                .eq(Message::getMessageId, messageId)
                .set(Message::getDelFlag, "2")));
    }
}
